package com.tieunguyen.truyencuoi;

import java.util.ArrayList;
import com.tieunguyen.beans.Category;
import com.tieunguyen.adapter.ListMenuAdapter;
import com.tieunguyen.util.DatabaseHelper;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class MainActivity extends ActionBarActivity {

	DrawerLayout dLayout;
	ListView listView;
	DatabaseHelper dbHelper;
	ArrayList<Category> categories = new ArrayList<Category>();
	Bundle bundle;
	ListMenuAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		dLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
		listView = (ListView)findViewById(R.id.left_drawer);
		dbHelper = new DatabaseHelper(this);
		categories = dbHelper.getCategory(this);
		adapter = new ListMenuAdapter(this, categories);
		listView.setAdapter(adapter);
		listView.setSelector(android.R.color.holo_blue_dark);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				dLayout.closeDrawers();
				bundle = new Bundle();
				bundle.putInt("catId", categories.get(position).getId());
				Fragment storyFragment = new ListStoriesFragment();
				storyFragment.setArguments(bundle);
				FragmentManager frm = getSupportFragmentManager();
				FragmentTransaction transaction = frm.beginTransaction();
				transaction.replace(R.id.content_frame, storyFragment);
				transaction.addToBackStack(null);
				transaction.commit();
			}
			
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
